package com.nlelpct.manage.controller;

import com.alibaba.fastjson2.JSON;
import com.nlelpct.manage.constant.ResponseCode;
import com.nlelpct.manage.context.ThreadParameter;
import com.nlelpct.manage.model.query.DeptTreeQuery;
import com.nlelpct.manage.model.query.InsertAndUpdateDeptQuery;
import com.nlelpct.manage.model.query.InsertAndUpdateRoleQuery;
import com.nlelpct.manage.model.vo.AddDepartmentVo;
import com.nlelpct.manage.model.vo.DepartmentTreesVo;
import com.nlelpct.manage.model.vo.EditDepartmentVo;
import com.nlelpct.manage.model.vo.ResponseResult;
import com.nlelpct.manage.service.SysDepartmentService;
import com.nlelpct.manage.utils.Nap;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/sysDepartment")
@Slf4j
public class SysDepartmentController {
    @Autowired
    private SysDepartmentService sysDepartmentService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @PreAuthorize("hasRole('admin')")
    @PostMapping(value = "/getDeptTree")
    @ResponseBody
    public ResponseResult<List<DepartmentTreesVo>> getDeptTrees(@RequestBody DeptTreeQuery deptTreeQuery) {
        return sysDepartmentService.getDepartmentTree(deptTreeQuery);
    }

    @PreAuthorize("hasRole('admin')")
    @PostMapping(value = "/addDepartment")
    @ResponseBody
    public ResponseResult addDepartment(@RequestBody @Validated InsertAndUpdateDeptQuery insertDeptQuery) {
        synchronized (stringRedisTemplate) {
            String key = "SysDepartmentController.addDepartment" + JSON.toJSONString(insertDeptQuery);
            if (!ObjectUtils.isEmpty(stringRedisTemplate.opsForValue().get(key))) {
                new Nap(0.3);
            }
            stringRedisTemplate.opsForValue().set(key, key, 300L, TimeUnit.MILLISECONDS);
        }
        ResponseResult<Boolean> booleanResponseResultByName = sysDepartmentService.validateDeptName(insertDeptQuery);
        if (!booleanResponseResultByName.getData()) {
            return ResponseResult.error(ResponseCode.ORDINARY_FAIL, "添加部门失败，名称重复。");
        }
        ResponseResult<Boolean> booleanResponseResultByNum = sysDepartmentService.validateDeptNum(insertDeptQuery);

        if (!booleanResponseResultByNum.getData()) {
            return ResponseResult.error(ResponseCode.ORDINARY_FAIL, "添加部门失败，编号重复。");
        }
        try {
            sysDepartmentService.addDepartment(insertDeptQuery);
        } catch (Exception e) {
            log.error("添加部门时出现异常,具体异常信息如下: ");
            e.printStackTrace();
            return ResponseResult.error(ResponseCode.ORDINARY_FAIL, "添加部门信息失败,请联系系统管理员");
        }
        return ResponseResult.success("添加部门成功");
    }


    @PreAuthorize("hasRole('admin')")
    @PostMapping(value = "/editDepartmentById")
    @ResponseBody
    public ResponseResult editDepartmentById(@RequestBody InsertAndUpdateDeptQuery updateDeptQuery) {
        ResponseResult<Boolean> booleanResponseResultByName = sysDepartmentService.validateDeptName(updateDeptQuery);
        if (!booleanResponseResultByName.getData()) {
            return ResponseResult.error(ResponseCode.ORDINARY_FAIL, "编辑部门失败，名称重复。");
        }
        ResponseResult<Boolean> booleanResponseResultByNum = sysDepartmentService.validateDeptNum(updateDeptQuery);

        if (!booleanResponseResultByNum.getData()) {
            return ResponseResult.error(ResponseCode.ORDINARY_FAIL, "编辑部门失败，编号重复。");
        }
        try {
            sysDepartmentService.editDepartmentById(updateDeptQuery);
        } catch (Exception e) {
            log.error("编辑部门时出现异常,具体异常信息如下: ");
            e.printStackTrace();
            return ResponseResult.error(ResponseCode.ORDINARY_FAIL, "编辑部门信息失败,请联系系统管理员");
        }
        return ResponseResult.success("编辑部门成功");
    }


    /**
     * 删除部门时校验是否可以删除
     */
    @PreAuthorize("hasRole('admin')")
    @GetMapping("/deleteDeptValidate/{roleId}")
    public ResponseResult<Boolean> deleteDeptValidate(@PathVariable("deptId") String deptId) {
        return sysDepartmentService.deleteDeptValidate(deptId);
    }

    /**
     * 添加部门-更新部门时判断部门名称是否重复
     */
    @PreAuthorize("hasRole('admin')")
    @PostMapping("/validateDeptName")
    public ResponseResult<Boolean> validateDeptName(@RequestBody @Validated InsertAndUpdateDeptQuery validateDeptNameQuery) {
        return sysDepartmentService.validateDeptName(validateDeptNameQuery);
    }

    /**
     * 添加部门-更新部门时判断部门编号是否重复
     */
    @PreAuthorize("hasRole('admin')")
    @PostMapping("/validateDeptNum")
    public ResponseResult<Boolean> validateDeptNum(@RequestBody @Validated InsertAndUpdateDeptQuery validateDeptNumQuery) {
        return sysDepartmentService.validateDeptNum(validateDeptNumQuery);
    }


    /**
     * 删除部门
     */
    @PreAuthorize("hasRole('admin')")
    @GetMapping("/deleteDept/{deptId}")
    public ResponseResult<String> deleteDept(@PathVariable("deptId") String deptId) {
        ResponseResult<Boolean> booleanResponseResult = sysDepartmentService.deleteDeptValidate(deptId);
        if (!booleanResponseResult.getData()) {
            return ResponseResult.error(ResponseCode.ORDINARY_FAIL, "当前部门不允许删除");
        }
        try {
            sysDepartmentService.removeDept(deptId);
        } catch (Exception e) {
            log.error("删除部门时出现异常,具体异常信息如下: ");
            e.printStackTrace();
            return ResponseResult.error(ResponseCode.ORDINARY_FAIL, "删除部门出错,请联系系统管理员");
        }
        return ResponseResult.success("删除部门完成");
    }


}
